package cn.edu.cdut.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Author  kobe
 * Created on 2017-06-21-19:40
 */
@Aspect
@Component
public class HttpAspect {

        private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

        @Pointcut("execution(public * cn.edu.cdut.controller.*.*(..))")
        public void cut() {} //切点名

        @Before("cut()")
        public void beforeLog(JoinPoint joinPoint) {

                //System.out.println("----- before -----");
                logger.info("----- before -----");
                //日志打印
                ServletRequestAttributes servletRequestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                HttpServletRequest request = servletRequestAttributes.getRequest();

                //request_url
                logger.info("url={}", request.getRequestURL());

                //request_method
                logger.info("method={}", request.getMethod());

                //controller_className_methodName
                logger.info("class_method={}", joinPoint.getSignature().getDeclaringTypeName() + "." +joinPoint.getSignature().getName());

                //args
                logger.info("args={}", joinPoint.getArgs());
        }

        @After("cut()")
        public void afterLog() {
                logger.info("----- after -----");
        }

        @AfterReturning(pointcut = "cut()", returning = "object")
        public void afterReturningLog(Object object) {
                //目标方法必须有个返回值，防止出现异常（空指针）
                logger.info("return={}", object.toString());
        }
}
